# -*- coding: utf-8
from .models import TinyShop,Product,Order,GoodsCategory,GoodsLib, ProductImage
import datetime
from django.utils import timezone
from api.views import error, render
from django.views.decorators.http import require_http_methods
from .form import ImageUploadForm
from django.shortcuts import render_to_response
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponse
import json
from copy import deepcopy
import base64
import requests
import cStringIO
import sys
import settings
import requests
from django.core.files.uploadedfile import InMemoryUploadedFile
from feserver import user
import md5
from store.models import TinyshopImage
from api.middlewares import ThreadLocal
from jfpal.generics import JSONResponse
import random
from django.db.models import Count
from django.db.models import Sum

NOTIFY_KEY = "ABCDEFG"

@require_http_methods(["POST"])
def tinyshopcreate(request):
    '''
        'store.tinyshop.create'
        create a new tiny shop
    '''
    mobile_no = request.POST.get('mobile_no')
    if TinyShop.objects.filter(mobile_no=mobile_no).exists():
        return error(u"不能重复建福店!")

    name = request.POST.get('name')
    #imageName =  request.POST.get('imageName')
    form = ImageUploadForm(request.POST, request.FILES)
    if not form.is_valid():
        return error(u"上传数据错误")
    tinyshop = TinyShop(name=name, mobile_no=mobile_no)
    tinyshop.image_id = 1
    tinyshop.save()
    return render({ "tinyshop": tinyshop })

def tinyshopupdate(request):
    '''
        'store.tinyshop.create'
        create a new tiny shop
    '''
    mobile_no = request.POST.get('mobile_no')
    try:
        t = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        return error(u"没有找到福店")
    
    t.name = request.POST.get('name')
    t.image_id = request.POST.get('image_id', 1)
    t.save()
    return render({ "tinyshop": t })



def tinyshoplogin(request):
    '''
    福店登陆。 在用户进入自己福店时，必须调用
    '''
    mobile_no = request.POST.get('mobile_no')
    username = request.POST.get('username')
    token = request.POST.get('token')
    if user.validToken(mobile_no, token):
        request.session['mobile_no'] = mobile_no
        
        try:
            t = TinyShop.objects.get(mobile_no = mobile_no)
        except:
            t = TinyShop(name=username, mobile_no=mobile_no)
            t.save()
        return render({ "tinyshop": t })
    else:
        return error(u"登陆无效")
    return render({ "tinyshop": t })
    

def tinyshopdetail(request):
    '''
        'store.tinyshop.detail'
        get the tiny shop detail. if tinyshop is not exists, create one.
    '''
    mobile_no = request.GET.get('mobile_no')
    if mobile_no == None:
        return error(u"参数错误")
    if mobile_no == "1":
        return error(u"没找到福店")
    try:
        if len(mobile_no) != 11:
            t = TinyShop.objects.get(pk=mobile_no)
        else:
            t = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        if len(mobile_no) != 11:
            return error(u"没找到福店")
        try:
            t = TinyShop.objects.get(mobile_no = mobile_no)
        except: 
            username = user.info(mobile_no)
            
            if username:
                #create 
                t = TinyShop(name=username.strip("*"), mobile_no=mobile_no, image_id=1)
                t.save()
            else:
                return error(u"没有找到福店")
        else:
            return error(u"没有找到福店")
    return render({ "tinyshop": t })

def tinyshopsearch(request):
    """
        store.tinyshop.search
        按照mobile no或名称搜索福店
    """
    search = request.GET.get('k')
    try:
        t = TinyShop.objects.get(id = search)
        if t:
            return render({ "tinyshop": t })
    except:
        pass

    try:
        t = TinyShop.objects.filter(name = search)
        if t:
            return render({ "tinyshop": t })
    except:
        pass
    try:
        t = TinyShop.objects.get(mobile_no = search)
        if t:
            return render({ "tinyshop": t })
    except:
        pass
    return error(u"没有发现任何相关福店！")


@require_http_methods(["POST"])
def productimagecreate(request):
    tinyshop_id = request.POST.get('tinyshop_id')
    form = ImageUploadForm(request.POST, request.FILES)
    if not form.is_valid():
        return error(u'数据错误')
    if form.cleaned_data['image'] == None:
        return error(u'图片不能为空')
    pi = ProductImage(tinyshop_id=tinyshop_id)
    pi.image = form.cleaned_data['image']
    pi.save()
    return render({ "image": pi })

    
@require_http_methods(["POST"])
def tinyshopimagecreate(request):
    tinyshop_id = request.POST.get('tinyshop_id')
    try:
        tinyshop = TinyShop.objects.get(pk=tinyshop_id)
    except:
        return error(u'数据错误')
    
    form = ImageUploadForm(request.POST, request.FILES)

    if not form.is_valid():
        return error(u'数据错误')
    if form.cleaned_data['image'] == None:
        return error(u'图片不能为空')
    
    pi = TinyshopImage()
    pi.image = form.cleaned_data['image']
    pi.save()
    return render({ "image": pi })
    
    
@require_http_methods(["POST"])
def productcreate(request):
    '''
        product create
    '''
    mobile_no = request.session.get('mobile_no')
    
    image_id = request.POST.get('image_id', None) 
    try:
        tinyshop = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        print u'福店不存在!', mobile_no;
        return error(u'福店不存在!')
    
    if tinyshop.mobile_no != mobile_no:
        print u'访问错误',tinyshop.mobile_no, mobile_no, tinyshop;
        return error(u'访问错误')

    name = request.POST.get('name')
    price = request.POST.get('price')
    information = request.POST.get('information')
    
    p = Product(name=name,price=price,information=information, image_id=image_id, tinyshop=tinyshop)
    p.save();

    return render({ "product": p })

def productdelete(request):
    '''
        product delete
    '''
    product_id = request.POST.get('product_id')
    mobile_no = request.session.get('mobile_no')

    try:
        p = Product.objects.get(pk=product_id, status=1)
    except:
        return error(u'产品不存在！')
    if p.tinyshop.pk == 1:
        return error('默认产品不可编辑。添加产品后，默认产品将被自动移除')
    if mobile_no != p.tinyshop.mobile_no:
        return error(u'访问错误')
    p.status = 0
    p.save()
    return render({ "product": p })


#product detail
def productdetail(request):
    product_id = request.GET.get('product_id')
    try:
        p = Product.objects.get(pk=product_id,status=1)
    except:
        return error(u'产品不存在！')
    return render({ "product": p })

#product update
@require_http_methods(["POST"])
def productupdate(request):
    product_id = request.POST.get('product_id')
    try:
        p = Product.objects.get(pk=product_id, status=1)
    except:
        return error(u'产品不存在!')
    if p.tinyshop.pk == 1:
        return error('默认产品不可编辑。添加产品后，默认产品将被自动移除')
    if p.tinyshop.mobile_no != request.session.get('mobile_no'):
        return error(u'访问错误')
    p.name = request.POST.get('name')
    p.price = request.POST.get('price')
    p.information = request.POST.get('information')
    p.image_id = request.POST.get('image_id');
    p.save()
    return render({ "product": p })

#product list
def productlist(request):
    mobile_no = request.GET.get('mobile_no')
    perpage = request.GET.get('perpage', 20)
    offset = request.GET.get('offset', 0)
    try:
        tinyshop = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        username = user.info(mobile_no)
        if username:
            tinyshop = TinyShop(name=username.strip("*"), mobile_no=mobile_no)
            tinyshop.save()
        else:
            return error(u'福店不存在!')
        
    cnt = tinyshop.product_set.filter(status=1).count()
    
    p_list = tinyshop.product_set.filter(status=1).order_by('-pk')[offset:perpage]
    if offset == 0 and p_list.count() == 0:
        p_list = Product.objects.filter(tinyshop_id=1).order_by('-pk')[offset:perpage]
        cnt = Product.objects.filter(tinyshop_id=1).count()
        
    return render({"product_list": p_list, "cnt": cnt})

#     serializer = ProductSerializer(p_list)
#     return JSONResponse(serializer.data)

#detail dispose
def detaildispose(detail):
    return json.loads(detail)


#order submit
@require_http_methods(["POST"])
def ordersubmit(request):
    mobile_no = request.POST.get('mobile_no')
    try:
        tinyshop = TinyShop.objects.get(mobile_no=mobile_no)
    except:
        return error(u'福店不存在!')
    
    time = timezone.now()
    payer = request.POST.get('payer_id')
    detail = request.POST.get('detail')
    amount = request.POST.get('amount')
    needexpress = (request.POST.get('needexpress') == "1")
    address = request.POST.get('address')
    memo = request.POST.get('memo', "")
    
    product_amount = 0
    detailList = detaildispose(detail)
    product_id_sub = 0
    product_price_sub = 1
    product_num_sub = 2
    product_detail_sub = 3
    
    if amount == 0:
        return error(u'金额不能为0')
    
    if len(detailList) == 0:
        return error(u'购物车为空')
    
    for product_inf in detailList:
        try:
            pk = product_inf[product_id_sub]
            
            if isinstance(pk, basestring) and pk.startswith("tmp-"):
                pd = product_inf[product_detail_sub]
                pd['name']  = pd['name'][0:80]
                foundProduct = Product.objects.filter(tinyshop=tinyshop, name=pd['name'], price=pd["price"]); 
                if foundProduct.count() > 0:
                    product = foundProduct[0]
                else:
                    if pd.get("image_src"):
                        pImage = ProductImage();
                        pImage.image = pd['image_src']
                        pImage.tinyshop = tinyshop
                        pImage.save()
                    else:
                        pImage = ProductImage.objects.get(1)
                    
                    product = Product(**{"name": pd['name'],"image":pImage, "price": pd["price"]})
                    product.tinyshop = tinyshop
                    product.save()
                    
                pk = product.pk
                
            p = Product.objects.get(pk=pk)
        except:
            return error(u'产品不存在!')
        #if p.price != decimal.Decimal(product_inf[product_price_sub]):
        #    return error(u"商品价格和数据库不匹配！")
        p_num = int(product_inf[product_num_sub])
        product_amount += p.price*p_num
    
    order = Order(amount=amount,payer=payer,detail=detail, product_amount=product_amount,
                      needexpress=needexpress, address=address,memo = memo
                      )

    tinyshop.order_set.add(order)
    tinyshop.save()

    order.save()
    return render({ "order": order })


#order submit
@require_http_methods(["POST"])
def orderpaid(request):
    order_id = request.POST.get('order_id')
    amount = request.POST.get('amount')
    payment = request.POST.get('pay_method')
    status = request.POST.get('order_satus')
    
    try:
        order = Order.objects.get(pk=order_id, status=1)
    except:
        return error(u'订单不存在!')
    if order.tinyshop.mobile_no != request.session.get('mobile_no'):
        return error(u'访问错误')

    if order.amount != amount:
        return error(u'金额错误！')
    
    if order.needexpress:
        order.status = Order.Processing
    else:
        order.status = Order.Completed
    order.payment = payment
    order.save()
    
    return render({ "order": order })

@require_http_methods(["POST"])
def orderupdate(request):
    order_id = request.POST.get('order_id')
    amount = request.POST.get('amount')
    payment = request.POST.get('pay_method')
    status = request.POST.get('status')
    action = request.POST.get('action')

    try:
        order = Order.objects.get(pk=order_id)
    except:
        return error(u'订单不存在!')
    if order.tinyshop.mobile_no != request.session.get('mobile_no'):
        return error(u'访问错误')

    #if order.amount != amount:
    #    return error(u'金额错误！')
    if order.status == Order.New and action == "update":
        order.amount = amount

    if order.status == Order.Processing and action=="finished":
        order.status = Order.Completed 

    if payment != None:
        order.payment = payment
    order.save()
    
    return render({ "order": order })

# def ordernotification(request):

#     orderId = request.GET.get('orderid')
#     
#     
#     order = 
    
#order notify
@require_http_methods(["GET"])
def orderget(request):
    '''
    http://pay.sulink.cn/goldkey/QueryOrder.aspx?orderid=213&sign=3663710AC843BAAD2F2ECF316C83A6B3
    MD5(Status =***& Remark =***&OrderId=***&Amount=***&FeeCode =***&DeadLine =*** +&+ 密钥)
    '''
    order_id = request.GET.get('OrderId')
    sign = request.GET.get('Sign')

    try:
        order = Order.objects.get(id = order_id)
    except:
        return error(u'订单不存在！')

    signStr = "OrderId=%s&%s" % (order_id, NOTIFY_KEY)
    if signStr != sign:
        return error(u'Sign 错误！')
    
    data = {
            'Status': "0000",
            "Remark": "Success",
            "OrderId": order_id,
            "Amount": order.amount,
            "FeeCode": 67,
            "DeadLine": "",
            "Sign": NOTIFY_KEY
            }
    sign2 = "Status=%(Status)s&Remark=%(Remark)s&OrderId=%(OrderId)s&Amount=%(Amount)s&FeeCode=%(FeeCode)s&DeadLine=%(DeadLine)s&%(Sign)s)" % data
    data['Sign'] = md5.md5( sign2 ).hexdigest();
    return render(data)



def notifyError(code="0001", message=u"操作失败"):
    context = {"Status":code,
               "Remark":message}
    signStr = u"Status=%s&Remark=%s&%s" % (code, message, NOTIFY_KEY) 
    sign = md5.md5(signStr)
    context['sign'] = sign
    return  JSONResponse(JSONResponse)

def notifySuccess(code="0000", message=u"操作成功"):
    context = {"Status":code,
               "Remark":message}
    signStr = u"Status=%s&Remark=%s&%s" % (code, message, NOTIFY_KEY) 
    sign = md5.md5(signStr)
    context['sign'] = sign
    return  JSONResponse(JSONResponse)

import hashlib
#order notify
@require_http_methods(["POST", "GET"])
def ordernotify(request):
    '''
    http://pay.sulink.cn/goldkey/PayNotify.aspx?OrderId=1111&Amount=1000&TransTime=20130828101802&TransID =111111&Status=00&Sign=0BD4AB6E5053F3F10CE1DA07061E3CD1
    OrderId=1111&Amount=1000&TransTime=20130828101802&TransID=111111&Status=0000& key
    curl --data "param1=value1&param2=value2" http://pro.jfpal.com/order/notify
    '''
    order_id = request.GET.get('OrderId', "").replace("2C", "")
    amount = request.GET.get('Amount')
    transtime = request.GET.get('TransTime')
    transID = request.GET.get('TransID')
    status = request.GET.get('Status')
    sign = request.GET.get('Sign')
    
    key = "EB551E49BCD34FC8C2A21BA3338D93E8"
    
    if len(order_id) == 19:
        #it is the v2 order, forward it!
        r = requests.get("http://pro2.jfpal.com/order/notify", params=request.GET)
        return  HttpResponse(r.text)
    
    try:
        order = Order.objects.get(id = order_id)
    except:
        return error(u'订单不存在！')
    
    #OrderId=1111&Amount=1000&TransTime=20130828101802&TransID=111111&Status=0000& key
    signStr = "OrderId=%s&Amount=%s&TransTime=%s&TransID=%s&Status=%s&%s" % (
                       order_id, amount, transtime, transID,   status, key )
    m = hashlib.md5()
    m.update(signStr)
    if m.hexdigest() != sign:
        return error(u'Sign 错误！')
    if abs(float(order.amount * 100) - int(amount)) > 0.001:
        return error(u'金额错误！')
    
    transTime = datetime.datetime.strptime(transtime, "%Y%m%d%H%M%S")
    now = timezone.localtime(timezone.now()).replace(tzinfo=None)
    delta = abs((transTime - now).total_seconds())
    
    if delta > 10 * 60:
        return error(u'时间错误！')
    if not(status == "0000" or status == "00"):
        return error(u'状态错误！')
    
    if order.needexpress:
        order.status = Order.Processing
    else:
        order.status = Order.Completed
    order.payment = Order.PAYMENT_BANK_CARD
    order.trans_id = transID
    order.save()
    
    data = {
            'Status': "0000",
            "Remark": "Success",
            "Sign": NOTIFY_KEY
            }
    sign2 = "Status=%(Status)s&Remark=%(Remark)s&%(Sign)s)" % data
    data['Sign'] = md5.md5( sign2 ).hexdigest();
    return render(data)


#order list
def orderlist(request):
    mobile_no = request.session.get('mobile_no')
    status = request.GET.get('status', "").split(",")
    if mobile_no == None:
        return error(u'登陆无效')
    try:
        tinyshop = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        return error(u'福店不存在!')
    
    order_list = tinyshop.order_set.filter(status__in=status).order_by('-pk')[:21]
    return render({ "orders": order_list })

#order list
def orderdetail(request):
    order_id = request.GET.get('order_id')
    mobile_no = request.session.get("mobile_no")
    try:
        order = Order.objects.get(id = order_id, tinyshop__mobile_no=mobile_no)
    except:
        return error(u'订单不存在！')
    
    products = []
    try:
        parr = json.loads(order.detail)
        for d in parr:
            p = Product.objects.get(pk=d[0])
            products.append({
                             "name": p.name,
                             "price": d[1],
                             "amount": d[2],
                             "img": "%s%s" % (settings.MEDIA_URL, p.image.image),
                             })
    except ValueError, e:
        pass
    return render({ "order": order, 'products': products })


#order list
def myorderlist(request):
    mobile_no = request.session.get('mobile_no')
    status = request.GET.get('status', "").split(",")
    if mobile_no == None:
        return error(u'登陆无效')
    
    order_list = Order.objects.filter(payer=mobile_no).filter(status__in=status).order_by('-pk')[:21]
    print mobile_no, status
    return render({ "orders": order_list })

#order list
def myorderdetail(request):
    order_id = request.GET.get('order_id')
    mobile_no = request.session.get("mobile_no")
    try:
        order = Order.objects.get(id = order_id, payer=mobile_no)
    except:
        return error(u'订单不存在！')
    
    products = []
    try:
        parr = json.loads(order.detail)
        for d in parr:
            p = Product.objects.get(pk=d[0])
            products.append({
                             "name": p.name,
                             "price": d[1],
                             "amount": d[2],
                             "img": "%s%s" % (settings.MEDIA_URL, p.image.image),
                             })
    except ValueError, e:
        pass
    return render({ "order": order, 'products': products })

def myorderupdate(request):
    pass

def test(request):
    output = _("Order not found")
    return HttpResponse(output)

def upload(request):
    if request.POST.get('file') and request.POST.get('name'):
        file = cStringIO.StringIO(base64.b64decode(request.POST['file']))
        image = InMemoryUploadedFile(file,
           field_name='file',
           name=request.POST['name'],
           content_type="image/jpeg",
           size=sys.getsizeof(file),
           charset=None)
        request.FILES[u'file'] = image

def goodscategory(request):
    category = GoodsCategory.objects.all()
    return render({ "goodscategory": category })

def goodslib(request):
    category_id = request.GET.get('category_id')
    try:
        category = GoodsCategory.objects.get(id=category_id)
    except:
        error(u"该分类不存在！")
    goods_lib = category.goodslib_set.filter(category=category)
    return render({ "goodslib": goods_lib })


def goodsdetail(request):
    goods_id = request.GET.get('id')
    try:
        goods = GoodsLib.objects.get(id=goods_id)
    except:
        return error(u"该默认商品不存在！")
    return render({ "goods": goods })



def tinytest(request):
    a = request.session.get("a")
    if a is None:
        a = 0
    request.session['a'] = a+1;
    return render({ "a": a })

def productcreatetest(request):
    return render_to_response('product_creat_test.html')





#reports
def reportdashboard(request):
    toDay = request.GET.get('to', (timezone.now() + datetime.timedelta(days=1)).strftime("%Y%m%d"))
    fromDay = request.GET.get('from', (datetime.datetime.strptime(toDay, "%Y%m%d") - datetime.timedelta(days=7)).strftime("%Y%m%d"))
    
    delta = request.GET.get('delta', 1)
    days = 1
    
    mobile_no = request.session.get('mobile_no')
    tinyshop = TinyShop.objects.get(mobile_no = mobile_no)
    try:
        tinyshop = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        return error(u'福店不存在!')
    
    rs = {}
    
    sales_data = {};
    
    endTime = datetime.datetime.strptime(toDay, "%Y%m%d")
    fromTime = datetime.datetime.strptime(fromDay, "%Y%m%d")
    
    rs['sales'] = {};
    rs['compare_sales'] = {};
    
    salesData = Order.objects.filter(status=Order.Completed) \
                             .filter(created_at__range=(fromTime, endTime)) \
                             .filter(tinyshop=tinyshop)
    
    rs['products'] = _get_pop_products(salesData)
    rs['sales'] = _get_sales(salesData, fromTime, endTime)
    
    
    return render(rs)

from MySQLdb.times import Date

def _get_sales(salesData, fromTime, endTime):
    sales = {}
    d2 = fromTime
    for d in salesData:
        dkey = d.created_at.strftime("%Y%m%d")
        if sales.get(dkey) is None:
            sales[dkey] = {"count": 0, "amount": 0, "date": dkey}
        sales[dkey]['count'] += 1
        sales[dkey]['amount'] += d.amount
    d2 = fromTime

    rs = []
    while(True):
        dkey = d2.strftime("%Y%m%d")
        if sales.get(dkey) is None:
            sales[dkey] = {"count": 0, "amount": 0, "date": dkey}
        rs.append(sales[dkey])
        d2 = d2 + datetime.timedelta(days=1)
        if d2 > endTime:
            break 
    return rs 

def _get_pop_products(salesData, count=5):
    tmpS = {}
    for d in salesData:
        jsonData = json.loads(d.detail)
        for j in jsonData:
            pid = str(j[0])
            tmpS[pid] = tmpS.get(pid,0) + int(j[2])
    
    productResultTmp = sorted(tmpS.items(), key=lambda x: x[1], reverse=True)[0:count]
    productResult = []
    for d in productResultTmp:
        p = Product.objects.get(pk=d[0])
        productResult.append([p.name, d[1]])
    return productResult

def reportdays(request):
    toDay = request.GET.get('to', datetime.datetime.strptime("%Y%m%d"))
    fromDay = request.GET.get('from', datetime.datetime.strptime(datetime.datetime.strftime(toDay) - datetime.timedelta(days=7)))
    
    mobile_no = request.session.get('mobile_no')
    try:
        tinyshop = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        return error(u'福店不存在!')
    
    return render({ "today_cnt": 0 })

def reportproducts(request):
    toDay = request.GET.get('to', datetime.datetime.strptime("%Y%m%d"))
    fromDay = request.GET.get('from', datetime.datetime.strptime(datetime.datetime.strftime(toDay) - datetime.timedelta(days=7)))
    
    endTime = datetime.datetime.strftime("%Y%m%d", toDay)
    fromTime = datetime.datetime.strftime("%Y%m%d", fromDay)
    
    mobile_no = request.session.get('mobile_no')
    try:
        tinyshop = TinyShop.objects.get(mobile_no = mobile_no)
    except:
        return error(u'福店不存在!')
    
    salesData = Order.objects.filter(status=Order.Completed) \
                             .filter(created_at__range=(fromTime, endTime)) \
                             .filter(tinyshop=tinyshop)
    
    rs = {}
    rs['products'] = _get_pop_products(salesData)
    
    return render({ "today_cnt": 0 })

